<script setup>
import {ref, h, onMounted} from 'vue'
import TreeSelectorDept from "@/components/TreeSelectorDept.vue";
import webConfig from '@/GlobalParas';
import axios from 'axios';
import { message, Modal } from 'ant-design-vue';
import AddUserModal from "@/views/systemUser/systemUserAddAndEdit.vue";
import UrlImg from "@/assets/yao.jpeg";
import { DeleteOutlined, HighlightOutlined } from '@ant-design/icons-vue';

let usersArr = ref([]);
let search_realName=ref('');
const suggestions = ref([]);

const selectedNode = ref(null);
const selectedNodeTitle = ref('')

function getUsers() {
  let url = webConfig.postUrl + '/systemUser/getAllUsers';

  axios.post(url)
    .then(res => {
      usersArr.value = res.data;
    })
    .catch(err => {
      message.error("获取用户信息失败");
    });
}

onMounted(() => {
  getUsers();
});
console.log(usersArr)

// 监听TreeSelectorDept组件的节点点击事件
function nodeClick(node){
  let url = webConfig.postUrl + '/systemUser/getUsersByDeptId';
  selectedNode.value = node.key;
  selectedNodeTitle.value = node.title;

  let deptId = node.key;

  axios.post(url, { deptId: deptId }
  ).then(res => {
    usersArr.value = res.data;
  }).catch(err => {
    message.error("获取部门用户信息失败");
  });
}

function handleSearch() {
  let url = webConfig.postUrl + '/systemUser/searchByName';

  if (selectedNode.value) {
    axios.post(url, { deptId: selectedNode.value, realName: search_realName.value }
    ).then(res => {
      usersArr.value = res.data;
      return
    }).catch(err => {

    });
  } else {
    let url = webConfig.postUrl + '/systemUser/searchAllByName';
    axios.post(url, { realName: search_realName.value }
    ).then(res => {
      usersArr.value = res.data;
      return
    }).catch(err => {

    })
  }
}

function querySearch(value) {
  if (!value) {
    suggestions.value = [];
    return;
  }

  let url = webConfig.postUrl + '/systemUser/searchByName';

  if (selectedNode.value) {
     axios.post(url, { deptId: selectedNode.value, realName: value }
    ).then(res => {
      suggestions.value = res.data.map(user => ({ value: user.realName, label: user.realName }));
    }).catch(() => {
      suggestions.value = [];
    });
  } else {
    let url = webConfig.postUrl + '/systemUser/searchAllByName';
    axios.post(url, { realName: value }
    ).then(res => {
      suggestions.value = res.data.map(user => ({ value: user.realName, label: user.realName }));
    }).catch(() => {
      suggestions.value = [];
    })
  }
}

function handleReset() {
  search_realName.value = '';
  let url = webConfig.postUrl + '/systemUser/getUsersByDeptId';

  if (selectedNode.value) {
    axios.post(url, { deptId: selectedNode.value }
    ).then(res => {
      usersArr.value = res.data;
    }).catch(err => {
      message.error("重置失败,请稍后再试");
    });
  } else {
    let url = webConfig.postUrl + '/systemUser/getAllUsers';
    axios.post(url)
      .then(res => {
        usersArr.value = res.data;
      })
      .catch(error => {

      })
  }
}

const handleDelete = (row) => {
  let url = webConfig.postUrl + '/systemUser/delUser';
  
  Modal.confirm({
    title: `确认删除用户 「${row.realName}」吗 ?`,
    onOk: () => {
      return axios.post(url, { tableKey: row.tableKey })
        .then((res) => {
          if (res.data === "success") {
            message.success('删除成功');
            // nodeClick({key: selectedNode.value});
            refreshList();
          } else {
            message.error('删除失败');
          }
        })
        .catch((error) => {
          if (error !== 'cancel' && error !== 'close') {
            message.error('删除失败');
          }
        });
    }
  })
}

const addUserDialogRef = ref(null);

function handleAdd() {
  if (!selectedNode.value) {
    message.warning('请先选择一个部门');
    return;
  }

  addUserDialogRef.value.openDialog({
    key: selectedNode.value,
    title: selectedNodeTitle.value
  });
}

function handleEdit(row) {
  row.deptName = selectedNodeTitle.value;
  addUserDialogRef.value.openDialog(row, true);
}

function refreshList() {
  if (selectedNode.value) {
    nodeClick({key: selectedNode.value});
  } else {
    getUsers();
  }
}

function onAddUserSuccess() {
  // nodeClick({key: selectedNode.value});
  refreshList();
}

function formatDate(datetimeStr) {
  if (!datetimeStr) return '';
  return datetimeStr.split(' ')[0].split('T')[0];
}
</script>

<template>
  <div style="width: 100%;height: 100%;background: #fff">
    <div class="deptContainer">
      <TreeSelectorDept @treeNodeClick="nodeClick"></TreeSelectorDept>
    </div>
    <div class="contentContainer">
      <div class="searchContainer">
        姓名：<a-auto-complete
          v-model:value="search_realName"
          :options="suggestions"
          placeholder="请输入姓名"
          @search="querySearch"
          style="width: 120px; margin-right: 10px;"
        />
        <a-button type="primary" @click="handleSearch">查询</a-button>
        <a-button type="default" @click="handleReset" style="color: #52c41a; border-color: #52c41a; margin-left: 10px;">重置</a-button>
      </div>
      <div class="addNewUser">
        <a-button type="primary" @click="handleAdd">添加新用户</a-button>
        <AddUserModal ref="addUserDialogRef" @success="onAddUserSuccess"></AddUserModal>
      </div>
      <a-table :data-source="usersArr" :pagination="false" row-key="tableKey" style="width: 100%;">
        <a-table-column title="姓名" data-index="realName" align="center"></a-table-column>
        <a-table-column title="头像" data-index="faceImg" align="center">
          <template #default="{ record }">
            <a-image
              :src="record.faceImg || UrlImg"
              style="width: 50px; height: 50px;z-index: 50;"
              :preview-src-list="record.faceImg ? [record.faceImg] : []"
              prewiew-teleported
              @error="(e) => { e.target.src = UrlImg}"
            ></a-image>
          </template>
        </a-table-column>
        <a-table-column title="职称" data-index="title" align="center"></a-table-column>
        <a-table-column title="学历" data-index="diploma" align="center"></a-table-column>
        <a-table-column title="教育经历" data-index="eudHistory" align="center"></a-table-column>
        <a-table-column
          title="出生日期"
          data-index="birth"
          align="center"
          :customRender="({ text }) => formatDate(text)"
        ></a-table-column>

        <a-table-column title="操作" align="center">
          <template #default="{ record }">
            <a-tag class="tagBtn1" style="background: #f00" title="删除" @click="handleDelete(record)">
              <DeleteOutlined />
            </a-tag>
            <a-tag class="tagBtn2" style="background: #1c3567" title="编辑" @click="handleEdit(record)">
              <HighlightOutlined />
            </a-tag>
          </template>
        </a-table-column>
      </a-table>
    </div>
  </div>
</template>

<style scoped>
.userImg {
  height: 120px;
  width: 90px;
}

.deptContainer{
  width:300px;
  height: 100%;
  float: left;
  border-right: 1px dashed #afafaf;
  margin-right: 5px;
}

.contentContainer{
  float:left;
  width:calc(100% - 310px);
  height: 100%;
  overflow-y: auto;
  overflow-x: hidden;
}

.searchContainer{
  height: 60px;
  line-height: 60px;
  text-align: center;
}

.addNewUser {
  margin-bottom: 10px;
}

.tagBtn1 {
  cursor: pointer;
  color: #fff;
}

.tagBtn2 {
  cursor: pointer;
  color: #fff;
}
</style>